<template>
  <div>
    <header style="display: flex; justify-content: space-between">
      <div style="display: flex">
        <h1>电路名：{{ circuitName }}</h1>
        <el-button
          style="margin-left: 20px; margin-top: -3px"
          @click="
            showDialog = true;
            console.log(fileUpload.value);
          "
          >修改
        </el-button>
      </div>
      <div>
        <el-button
          type="primary"
          style="
            margin-right: 20px;
            margin-top: -3px;
            height: 35px;
            font-size: 18px;
            background-color: #595959;
          "
          @click="back"
          >关闭该页面
        </el-button>
      </div>
    </header>
    <main style="display: flex; justify-content: center; align-items: center">
      <el-card style="width: 90%; display: flex; justify-content: center">
        <el-scrollbar
          max-height="650px"
          style="width: 100%; height: auto; display: flex"
        >
          <el-form
            :model="configForm"
            label-width="300px"
            style="width: 100%; flex-direction: column; font-size: 30px"
            size="large"
          >
            <el-form-item>
              <el-button type="danger" size="default" @click="clearAllFiles">
                清空所有文件
              </el-button>
            </el-form-item>
            <el-form-item
              label="是否修改sp文件中的温度值:"
              style="margin-bottom: 10px"
            >
              <el-checkbox v-model="caseSelected"></el-checkbox>
            </el-form-item>
            <el-form-item
              v-for="(item, index) in formItems"
              :key="index"
              :label="handleLabel(item.txt)"
              :prop="item.prop"
              style="margin-bottom: 10px"
            >
              <el-upload
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :accept="item.accept"
                @change="handleFileChange(item.prop, $event)"
              >
                <el-input
                  v-if="configForm[item.label]"
                  v-model="configForm[item.label]"
                  class="inputStyles"
                  readonly
                ></el-input>
                <el-input
                  v-else
                  v-model="configForm[item.prop]"
                  class="inputStyles"
                  readonly
                ></el-input>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-scrollbar>
        <div
          style="display: flex; align-items: center; justify-content: center"
        >
          <el-button
            type="primary"
            @click="uploadConfig"
            style="font-size: 20px; height: 35px; background-color: #003f82"
            >上传配置
          </el-button>
        </div>
      </el-card>
    </main>
    <!-- 弹窗 -->
    <el-dialog title="修改电路名" v-model="showDialog" width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="原电路名">
          <el-input v-model="form.old_circuit_diagram_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="新电路名">
          <el-input v-model="form.new_circuit_diagram_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="电路配置">
import { onActivated, ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {
  reCircuitName,
  huada_config_upload,
  getUploadFiles,
  huada_config_upload_pre,
} from "@/server/circuit";
import router from "@/router/index.js";

const caseSelected = ref(false);
const route = useRoute();
const circuitName = ref("...");
const configFile = ref({});
const fileUpload = ref({});
const configForm = ref({ 电路名称: route.params.circuitName });
const formItems = [
  {
    txt: "默认sp文件",
    label: "默认sp文件",
    prop: "property1",
    accept: ".sp",
  },
  {
    txt: "电路结构netlist文件",
    label: "电路结构netlist文件",
    prop: "property2",
    accept: ".netlist",
  },
  {
    txt: "温度mod默认文件",
    label: "温度mod默认文件",
    prop: "property3",
    accept: ".mod",
  },
  {
    txt: "AI_fixed文件",
    label: "AI_fixed文件",
    prop: "property4",
    accept: ".txt",
  },
  {
    txt: "AI_change文件",
    label: "AI_change文件",
    prop: "property5",
    accept: ".txt",
  },
  {
    txt: "低温mod文件",
    label: "温度mod文件1",
    prop: "property6",
    accept: ".mod",
  },
  {
    txt: "高温mod文件",
    label: "温度mod文件2",
    prop: "property7",
    accept: ".mod",
  },
  {
    txt: "ra文件",
    label: "ra文件",
    prop: "property8",
    accept: ".txt",
  },
  {
    txt: "蒙特卡洛sp文件",
    label: "蒙特卡洛sp文件",
    prop: "property9",
    accept: ".sp",
  },
  {
    txt: "蒙特卡洛netlist文件",
    label: "蒙特卡洛netlist文件",
    prop: "property10",
    accept: ".netlist",
  },
  {
    txt: "蒙特卡洛AI_fixed文件",
    label: "蒙特卡洛温度mod默认文件",
    prop: "property11",
    accept: ".mod",
  },
  {
    txt: "蒙特卡洛AI_change文件",
    label: "蒙特卡洛ra文件",
    prop: "property12",
    accept: ".txt",
  },
];

const back = () => {
  router.back();
};
const handleLabel = (label) => {
  const specialLabels = [
    "默认sp文件",
    "电路结构netlist文件",
    "温度mod默认文件",
    "AI_fixed文件",
    "AI_change文件",
  ];
  if (specialLabels.includes(label)) {
    return `* ${label}:`;
  }
  return `${label}:`;
};
const fileMap = {};
formItems.forEach((item) => {
  const fileNameWithoutExtension =
    item.label.replace(/:.*/, "").trim().replace(/\s/g, "") + "_n";
  fileMap[fileNameWithoutExtension] = item.label;
});
// 构建FormData的函数，方便复用和分离逻辑
const buildFormData = (fileUpload, formItems, configForm, caseSelected) => {
  const formData = new FormData();
  if (fileUpload != null) {
    formData.append("是否修改sp文件中的温度值", caseSelected.value ? 1 : 0);
    if(configForm.电路名称){
      formData.append("电路名称", configForm.电路名称);
    }else{
      formData.append("电路名称", circuitName.value);
    }
    for (const item of formItems) {
      formData.append(
        item.label.replace(":", "").trim(),
        fileUpload[item.prop]
          ? fileUpload[item.prop].raw
          : fileUpload[item.label.replace(":", "").trim()]
      );
    }
  }
  return formData;
};

// 统一的错误提示函数，减少重复代码
const showUploadError = () => {
  console.log(response);
  confirm("上传失败，请检查电路信息，是否缺少文件或者已拥有演算结果");
  ElMessage.error("上传失败");
};

const getUploadFile = async () => {
  try {
    const response = await getUploadFiles({
      circuit_diagram_name: route.params.circuitName,
    });
    console.log(response);
    for (const [key, value] of Object.entries(response)) {
      if (key.endsWith("_n")) {
        const fileName = key;
        // console.log(fileName)
        const _nFileName = value;
        const fileContentKey = key.replace(/_n$/, "_c");
        if (response.hasOwnProperty(fileContentKey)) {
          const fileContent = response[fileContentKey];
          const blob = new Blob([fileContent], {
            type: "text/plain",
          });
          const file = new File([blob], _nFileName, {
            type: "text/plain",
          });
          if (fileMap[fileName]) {
            fileUpload.value[fileMap[fileName]] = file;
            configForm.value[fileMap[fileName]] = file.name;
            console.log(fileMap[fileName]);
          } else {
            console.log("2", fileName);
            console.log("2", fileMap);
            console.log(`Unknown file: ${fileName}`);
          }
        } else {
          console.error(`Content for file ${fileName} not found`);
        }
      }
    }
    console.log("console.log(fileUpload.value):", fileUpload.value);
  } catch (e) {
    console.error("e:", e);
    ElMessage.info("请上传文件");
  }
};
// 处理文件选择变化
function handleFileChange(property, event) {
  const file = event;
  console.log(file);
  fileUpload.value[property] = file;
  console.log(fileUpload.value);
  if (file && file.raw) {
    configForm.value[property] = file.name;
    configFile.value[property] = file.name;
  } else {
    console.log("No file found or file structure is unexpected.");
  }
}

// 上传配置
async function uploadConfig() {
  if (
    configForm.value.property1 == "" ||
    configForm.value.property2 == "" ||
    configForm.value.property3 == "" ||
    configForm.value.property4 == "" ||
    configForm.value.property5 == ""
  ) {
    const shouldContinue = confirm("请先上传必须文件");
    if (!shouldContinue) {
      ElMessage.error("操作失败");
      return;
    }
  }

  let response;
  try {
    const formData = buildFormData(
      fileUpload.value,
      formItems,
      configForm.value,
      caseSelected.value
    );
    response = await huada_config_upload_pre(formData);
    console.log(response);
    if (
      response.content &&
      (response.content != null || response.content != "")
    ) {
      const isConfirm = confirm(`${response.content},请确认是否继续`);
      if (isConfirm) {
        try {
          await huada_config_upload(formData);
          ElMessage.success("上传成功");
        } catch (e) {
          showUploadError();
        }
      }
    } else {
      try {
        await huada_config_upload(formData);
        ElMessage.success("上传成功");
      } catch (e) {
        showUploadError();
      }
    }
  } catch (e) {
    console.error(e);
    showUploadError();
  }
}

const showDialog = ref(false); // 控制弹窗显示隐藏
const form = ref({
  old_circuit_diagram_name: "",
  new_circuit_diagram_name: "",
});
const submitForm = async () => {
  if (form.value.new_circuit_diagram_name.trim() === "") {
    ElMessage.error("新电路名不能为空");
    return;
  }
  try {
    await reCircuitName(form.value);
    circuitName.value = form.value.new_circuit_diagram_name;
    showDialog.value = false; // 关闭弹窗
    ElMessage.success("电路名修改成功");
    router.push({
      name: "电路配置",
      params: {
        circuitName: circuitName.value,
      },
    });
  } catch (e) {
    showDialog.value = false;
    confirm("修改失败，电路可能存在仿真结果或电路名重复");
  }
};

const clearAllFiles = () => {
  const isConfirm = confirm(
    "本清空文件功能，只能清除非标注必选的文件，且为了防止误操作，需要手动点击上传配置按钮，是否继续？"
  );
  if (isConfirm) {
    for (const item of formItems) {
      if (fileUpload.value[item.prop]) {
        fileUpload.value[item.prop] = null;
        configForm.value[item.prop] = "";
      }
    }
  }
};

onActivated(()=>{
  configForm.value={}
  circuitName.value = route.params.circuitName;
  form.value.old_circuit_diagram_name = circuitName.value;
  getUploadFile();
})

onMounted(async () => {
  circuitName.value = route.params.circuitName;
  form.value.old_circuit_diagram_name = circuitName.value;
  getUploadFile();
});
</script>

<style scoped>
.inputStyles {
  width: 850px;
}

header {
  padding: 20px;
  background-color: #f8f9fa;
}

main {
  margin-top: 20px;
}

footer {
  text-align: center;
  margin-top: 20px;
}

.el-tag {
  margin: -5px 0 -15px 0;
}
</style>
